﻿using System;
using System.Collections;
using LzmaHelper;
using UnityEngine;
using System.IO;

namespace MyAssetBundles {
    public class DecompressFolderProgress : FolderProgress {
        protected override void ShowProgress ()
        {
            string info = string.Format("process number: {0}k, total number: {1}k, progress: {2}%", target.processNum / 1000, target.totalNum / 1000, target.progress * 100);
            ShowProgress("Decompress", info);
        }
    }

    public class DecompressFolder : CoderFolder, IFolder, IFolderEnumerator{
        public ulong _codeOneBlockSpeed = 1024 * 126;
        public void Generate (string path, IFolderProgress progress)
        {
            SetProgress(progress, _outTotalSize);
            LzmaParams myParams = CreateCoderParams(path);
            AddAutoDeleteFile(myParams.outputPath);
            LzmaCoder.Decompress(ref myParams);
            if (myParams.error != null)
            {
                Debug.Log("Error: Coder");
            }
        }

        public IEnumerator GenerateEnumerator (string path, IFolderProgress progress)
        {
            SetProgress(progress, _outTotalSize);
            LzmaParams myParams = CreateCoderParams(path);
            AddAutoDeleteFile(myParams.outputPath);

            SevenZip.Compression.LZMA.Decoder decoder = gameObject.AddComponent<SevenZip.Compression.LZMA.Decoder>();
            decoder.CodeOneBlockSpeed = _codeOneBlockSpeed;
            FileStream inputFS = new FileStream(myParams.inputPath, FileMode.Open);
            FileStream outputFS = new FileStream(myParams.outputPath, FileMode.Create);
            const int propertiesSize = 5;
            byte[] properties = new byte[propertiesSize];
            inputFS.Read(properties, 0, properties.Length);
            decoder.SetDecoderProperties(properties);
            yield return decoder.CodeEnumerator(inputFS, outputFS, inputFS.Length, myParams.outputSize, myParams.progress);
            outputFS.Flush();
            outputFS.Close();
            inputFS.Close();
            yield return new WaitForEndOfFrame();
        }

        public override void SetProgress (long inSize, long outSize)
        {
            SetProcessNum(outSize);
        }
    }
}

